//
//  LZRecoveryPasswordViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/16.
//  Copyright © 2017年 XBN. All rights reserved.
//

typedef NS_ENUM(NSInteger, RecoveryType) {
    kRecoveryType_phone = 1,
    kRecoveryType_email = 2
};

#import "LZRecoveryPasswordViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "LZNewResetPasswordViewController.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZAreaCodeViewController.h"
#import "LZUserInfoPresenter.h"
#import "UIView+Rotation.h"
#import "LZRemindView.h"
#import "LZAlertView.h"
#import "extobjc.h"

@interface LZRecoveryPasswordViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *subTitleLabel;
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UILabel *areaCodeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *arrwoImg;
@property (weak, nonatomic) IBOutlet UIButton *verificationCodeBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeDownLabel;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTF;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userNameTFTopToSubTitleCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nextStepTopVerificationCodeTFCST;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTopToSuperViewCST;
@property (weak, nonatomic) IBOutlet UIView *line;

@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (strong, nonatomic) UINavigationController *navVC;
@property (strong, nonatomic) LZAreaCodeViewController *areaCodeVC;
@property (nonatomic, strong) NSTimer * timer;          //验证码倒计时
@property (nonatomic, strong) NSString * verifiCode;    //当前验证码
@property (nonatomic, assign) int count;
@property (nonatomic, assign) RecoveryType recoveryType; //操作 1 手机找回密码 2  邮箱找回密码  进入页面默认手机找回

@end

@implementation LZRecoveryPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureUI];
    
    [self configNavigationBar];
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

- (void)navbarBackButtonClickAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private 

/**
  获取手机验证码
 */
- (void)getVerificationCodeForPhone
{
    if (self.userNameTF.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        DLog(@"输入手机号");
        return;
    }
    //验证码类型（1注册，2快捷登录，3身份验证，4绑定手机）
    NSString * mobileStr = [NSString stringWithFormat:@"%@%@",
                            self.areaCodeLabel.text,
                            self.userNameTF.text];
    
    //显示倒计时
    [self startTimer];
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter userGetVerificationPhoneNum:mobileStr andonSuccess:^(id data) {
        
        DLog(@"获取验证码：\r%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        self.verifiCode = [NSString stringWithFormat:@"%@", [data objectForKey:@"data"]];
        
    } onFail:^(NSString *fail) {
        
        DLog(@"获取验证码失败：\r%@", fail);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        [self stopTimer];
        
        if ([fail isEqualToString:@"9999999"]) {
//            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
//                             andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                             andImage:[UIImage imageNamed:@"错误提示"]
                                                    cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
            
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                             andContent:LZLocalizedString(@"vificode_failed", nil)];
            
        }
    } ];

}


/**
 获取邮箱验证码
 */
- (void)getVerificationCodeForEmail
{
    if (self.userNameTF.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"login_alert_enter_eMail_address", @"")];
        DLog(@"输入邮箱");
        return;
    }
   
    NSString * emailStr = [NSString stringWithFormat:@"%@",self.userNameTF.text];
    
    //显示倒计时
    [self startTimer];
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    @weakify(self);
    [self.userInfoPresenter getVerificaitonCodeForEmail:emailStr Success:^(NSString *codeStr) {
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        
        self.verifiCode = codeStr;


    } Failure:^(NSString *fail) {
        DLog(@"获取验证码失败：\r%@", fail);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        [self stopTimer];
        
        [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"]
                         andContent:LZLocalizedString(@"vificode_failed", nil)];
    }];
}


- (void)openAreaCodeVC
{
    [self presentViewController:self.navVC animated:YES completion:^{
        
    }];
    @weakify(self);
    self.areaCodeVC.SelectedAreaCodeBlock = ^(NSString *codeStr){
        @strongify(self);
        self.areaCodeLabel.text = codeStr;
    };
}

- (void)changeViewShowForOperationType
{
    if (self.recoveryType == kRecoveryType_phone) { //
        
        self.subTitleLabel.text = LZLocalizedString(@"recovery_password_phone", nil);
        
        self.areaCodeLabel.hidden = NO;
        self.arrwoImg.hidden = NO;
        self.timeDownLabel.hidden = YES;

        self.userNameTF.placeholder = LZLocalizedString(@"register_by_phone", nil);
        
    }else if (self.recoveryType == kRecoveryType_email){
        
        self.subTitleLabel.text = LZLocalizedString(@"recovery_password_email", nil);
        
        self.areaCodeLabel.hidden = YES;
        self.arrwoImg.hidden = YES;
        self.timeDownLabel.hidden = YES;
        
        self.userNameTF.placeholder = LZLocalizedString(@"register_by_email", nil);
    }
}

#pragma mark - 倒计时 开启 关闭倒计时
- (void)startTimer {
    
    self.timeDownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    
    self.timeDownLabel.hidden = NO;
    self.verificationCodeBtn.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.timeDownLabel.hidden = YES;
    self.verificationCodeBtn.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.timeDownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.timeDownLabel.hidden = YES;
        self.verificationCodeBtn.hidden = NO;
    }
}


#pragma mark - textfield delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    NSInteger totalLength = textField.text.length;
    NSInteger replaceLength = string.length;
    NSInteger changeLength = range.length;
    if (totalLength + replaceLength - changeLength > 1) {
        self.verificationCodeBtn.highlighted = YES;
        self.verificationCodeBtn.userInteractionEnabled = YES;
    }else{
        self.verificationCodeBtn.highlighted = NO;
        self.verificationCodeBtn.userInteractionEnabled = NO;
    }
    
    return YES;
}

#pragma mark - UI
- (void)configureUI
{
    self.umLogPageViewName = @"找回密码";
    self.titleLabel.text = LZLocalizedString(@"password_recovery", nil);
    self.view.backgroundColor = UIColorFromRGB(0x333333, 1);
    self.line.backgroundColor = UIColorFromRGB(0x999999, 1);
    _userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    
    
    if ([GVUserDefaults standardUserDefaults].phoneAreaCode.length > 0) {
        self.areaCodeLabel.text = [GVUserDefaults standardUserDefaults].phoneAreaCode;
    }
    [self lz_setCustomBarAlpha:0];
    
    if (self.isRecoveryPasswordByPhone) {
        self.recoveryType = kRecoveryType_phone;
        self.userNameTF.keyboardType = UIKeyboardTypeNumberPad;
        self.verificationCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    }else{
        self.recoveryType = kRecoveryType_email;
        self.userNameTF.keyboardType = UIKeyboardTypeDefault;
        self.verificationCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    [self changeViewShowForOperationType];
    
    [self.arrwoImg setLanguageRotaion];
    
    self.titleLabel.text = LZLocalizedString(@"password_recovery", nil);
    
    self.verificationCodeBtn.userInteractionEnabled = NO;
    
    self.timeDownLabel.layer.cornerRadius = 3.;
    self.timeDownLabel.layer.masksToBounds = YES;
    self.timeDownLabel.layer.borderColor = UIColorFromRGB(0xcccccc, 1).CGColor;
    self.timeDownLabel.layer.borderWidth = 1;
    
    GET_SCREEN_SCALE(scale);
    self.areaCodeLabel.font = [UIFont systemFontOfSize:17*scale];
    
    self.userNameTF.delegate = self;
    self.userNameTF.font = [UIFont systemFontOfSize:17*scale];
    [self.userNameTF setTintColor:UIColorFromRGB(0x33a928, 1)];
    [self.userNameTF setValue:UIColorFromRGB(0x999999, 1) forKeyPath:@"_placeholderLabel.textColor"];
    
    self.verificationCodeTF.font = [UIFont systemFontOfSize:17*scale];
    self.verificationCodeTF.placeholder = LZLocalizedString(@"change_verificode", nil);
    [self.verificationCodeTF setTintColor:UIColorFromRGB(0x33a928, 1)];
    [self.verificationCodeTF setValue:UIColorFromRGB(0x999999, 1) forKeyPath:@"_placeholderLabel.textColor"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openAreaCodeVC)];
    self.areaCodeLabel.userInteractionEnabled = YES;
    [self.areaCodeLabel addGestureRecognizer:tap];
    
    self.logoTopToSuperViewCST.constant = 79*scale;
    self.userNameTFTopToSubTitleCST.constant = 80 *scale;
    self.nextStepTopVerificationCodeTFCST.constant = 90 *scale;

}

- (void)configNavigationBar{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 60, 40);
    [btn addTarget:self action:@selector(navbarBackButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back_en"];
    [btn setImage:image_back forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(btn.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [btn setLanguageRotaion];
    }
    
    [self hiddenBarNavigationItemSetting:@[btn] type:NAVIGATIONITEMSETTING_LEFT];
    [self lz_setCustomBarAlpha:0];
}


#pragma mark - btn action
- (IBAction)getVerificationCodeBtnAction:(id)sender {
    
    if (self.recoveryType == kRecoveryType_phone) {
        [self getVerificationCodeForPhone];
    }else{
        [self getVerificationCodeForEmail];
    }
}

- (IBAction)nextStepBtnAction:(id)sender {
    
//    if (self.verifiCode == nil) {
//        return;
//    }
//    else if (![self.verificationCodeTF.text isEqualToString:self.verifiCode]) {
//        return;
//    }
    
    if (self.verificationCodeTF.text.length == 0) {
        return;
    }
    LZNewResetPasswordViewController * vc = [[LZNewResetPasswordViewController alloc] initWithNibName:@"LZNewResetPasswordViewController" bundle:nil];
    if (self.recoveryType == kRecoveryType_phone) {
        vc.isResetByPhone = YES;
        vc.cellPhone = [NSString stringWithFormat:@"%@%@",
                        self.areaCodeLabel.text,
                        self.userNameTF.text];
        vc.verificationStr = self.verificationCodeTF.text;
    }else{
        vc.isResetByPhone = NO;
        vc.email = self.userNameTF.text;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 控件初始化
- (UINavigationController *)navVC
{
    if (!_navVC) {
        _navVC = [[UINavigationController alloc] initWithRootViewController:self.areaCodeVC];
        _navVC.navigationBar.translucent = NO;
        _navVC.navigationBar.barTintColor = [UIColor blackColor];
        _navVC.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]};
    }
    
    return _navVC;
}

- (LZAreaCodeViewController *)areaCodeVC
{
    if (!_areaCodeVC) {
        _areaCodeVC = [[LZAreaCodeViewController alloc] initWithNibName:@"LZAreaCodeViewController" bundle:nil];
    }
    
    return _areaCodeVC;
}
@end
